package com.aviation.sell_ticket.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.aviation.sell_ticket.mapper.ModelSeatMapper;
import com.aviation.sell_ticket.pojo.Aviation_city;
import com.aviation.sell_ticket.pojo.Aviation_model_seat;
import com.aviation.sell_ticket.service.ModelSeatService;
import com.aviation.sell_ticket.tool.RedisUtil;
import com.aviation.sell_ticket.tool.ResultEnum;
import com.aviation.sell_ticket.tool.ResultUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class ModelSeatServiceImpl implements ModelSeatService {

    @Resource
    ModelSeatMapper modelSeatMapper;

    @Resource
    private RedisUtil redis;//引入redis

    /**
     * 根据型号查询座位
     * @param modelId 航班型号
     * @return List<Aviation_model_seat>
     */
    @Override
    public List<Aviation_model_seat> querySeat(Integer modelId) {
        JSONArray SeatArray = null;
        List<Aviation_model_seat> modelSeats =null;
        //从缓存中提取数据
        String SeatData = redis.getRedis("modelSeat:" + modelId);
        //判断缓存是否存在
        if (null == SeatData) {
            //从数据库提取数据
            modelSeats = modelSeatMapper.querySeat(modelId);
            //转换json
            SeatArray = JSONArray.parseArray(JSON.toJSONString(modelSeats));
            //添加数据进缓存
            redis.setRidesTime("modelSeat:" + modelId, SeatArray.toJSONString(), (long) (60 * 60), TimeUnit.SECONDS);
        } else {
            //缓存中有数据
            modelSeats = JSONArray.parseArray(SeatData, Aviation_model_seat.class);
        }
        return modelSeats;
    }

    @Override
    public Aviation_model_seat SeatData(Integer modelId, String seatId) {
        JSONArray SeatArray = null;
        List<Aviation_model_seat> modelSeats =null;
        //从缓存中提取数据
        String SeatData = redis.getRedis("modelSeat:" + modelId);
        //判断缓存是否存在
        if (null == SeatData) {
            //从数据库提取数据
            modelSeats = modelSeatMapper.querySeat(modelId);
            //转换json
            SeatArray = JSONArray.parseArray(JSON.toJSONString(modelSeats));
            //添加数据进缓存
            redis.setRidesTime("modelSeat:" + modelId, SeatArray.toJSONString(), (long) (60 * 60), TimeUnit.SECONDS);
            //再次查询缓存
            SeatData = redis.getRedis("modelSeat:" + modelId);
        }
        //提取数据
        modelSeats = JSONArray.parseArray(SeatData, Aviation_model_seat.class);

        for (Aviation_model_seat seat : modelSeats) {
            if(seatId.equals(seat.getSeat_id())){
                return seat;
            }
        }
        return null;
    }


}
